# coding=utf-8
import os

from jproperties import Properties

from tools.OperationError import OperationError
from webapp.config import Config


class PropertiesUtils:
    def saveProperties(self, path, key, data):

        if path == None or len(path) <= 0:
            raise OperationError(-1, "path is None")

        if key == None or len(key) <= 0:
            raise OperationError(-1, "key is None")

        if data == None or len(data) <= 0:
            raise OperationError(-1, "data is None")

        print(path)
        p = Properties()
        file_dir = os.path.split(path)[0]
        if not os.path.isdir(file_dir):
            os.makedirs(file_dir)
        # 已存在文件
        if os.path.exists(path):
            props = p.load(path)
            props.__setitem__(key, Properties.escape(str(data)))
            # 全部遍历下
            for prop in props:
                props.__setitem__(prop, Properties.escape(props[prop]))
            # 保存文件
            props.save(path)
        else:
            p.__setitem__(key, Properties.escape(str(data)))
            # 保存文件
            p.save(path)

    def getProperties(self, path, key):

        if path == None or len(path) <= 0:
            raise OperationError(-1, "path is None")

        if key == None or len(key) <= 0:
            raise OperationError(-1, "key is None")

        print(path)
        p = Properties()
        props = p.load(path)
        dictret = props.get(key, {});
        print(type(dictret))
        if len(dictret) > 0:
            dictret = eval(str(dictret))
        else:
            dictret = {}

        return dictret


if __name__ == "__main__":

    filename = Config.ROOT_PATH + os.sep + r"initconfig" + os.sep + "master.properties"
    s = PropertiesUtils()
    arrs = s.getProperties(filename,Config.KEY_STORE)
    print(arrs)
    storeID = arrs.get("CP_C_STORE_ID", "")
    print(type(arrs))

